﻿using System;
using System.IO;
using System.Web.Mvc;
using DTTB.Common;

namespace DTTB.MV2.QUANLYNHANSUTIENLUONG.BussinessDelegate.CommonDelegate
{
    public class DownloadDelegate : ActionResult
    {
        public string FileName { get; set; }

        public string Path { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            string absolutePath = string.Empty; // Đường dẫn tuyệt đối của file
            absolutePath = Path + "\\" + FileName;

            if(!File.Exists(absolutePath))
            {
                context.HttpContext.Response.Redirect("~/Authentication/FileNotExist");
            }
            else
            {
                context.HttpContext.Response.Buffer = true;

                context.HttpContext.Response.Clear();

                FileName = FileName.Replace(" ","_");

                context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + FileName + ";");

                context.HttpContext.Response.ContentType = "application/octet-stream";
                context.HttpContext.Response.ContentEncoding = System.Text.Encoding.UTF8;

                Byte[] bytes = Utils.GetFileByte(absolutePath);
                context.HttpContext.Response.OutputStream.Write(bytes, 0, bytes.Length);
                //context.HttpContext.Response.WriteFile(absolutePath);
                context.HttpContext.Response.End();
            }
        }

    }
}